#include <Mp3EncoderI.h>
#include <Ice/Ice.h>

using namespace std;
using namespace Ripper;

Mp3EncoderI::Mp3EncoderI(int channels,
			 int rate)
{
  lame_set_num_channels(_gfp, channels);
  lame_set_in_samplerate(_gfp, rate);
  lame_set_brate(_gfp,192);
  lame_set_bWriteVbrTag(_gfp,0);
  lame_init_params(_gfp);
}

Mp3EncoderI::~Mp3EncoderI()
{
  lame_close(_gfp);
}

Ice::ByteSeq
Mp3EncoderI::encode(const ::Ice::ShortSeq& leftSamples,
		    const ::Ice::ShortSeq& rightSamples,
		    const ::Ice::Current& current)
{
  long nsamples = leftSamples.size();
  unsigned long sz = static_cast<unsigned long>(1.25f*nsamples + 7200);
  if(_data.capacity() < sz)
    {
      _data.reserve(sz);
    }
  _data.resize(sz);
  int n = lame_encode_buffer(_gfp, &leftSamples[0], &rightSamples[0], nsamples, &_data[0], _data.size());
  if(n < 0)
    {
      throw EncodingFailedException();
    }
  _data.resize(n);
  return _data;
}

Ice::ByteSeq
Mp3EncoderI::flush(const ::Ice::Current& current)
{
  current.adapter->remove(current.id);

  unsigned long sz = 7200;
  if(_data.capacity() < sz)
    {
      _data.reserve(sz);
    }
  _data.resize(sz);
  int n = lame_encode_flush(_gfp, &_data[0], _data.size());
  if(n < 0)
    {
      throw EncodingFailedException();
    }
  _data.resize(n);
  return _data;
}
